<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="back-btn" @click="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <text class="title">任务管理</text>
      <view class="action-btn" @click="showActions">
        <text class="iconfont icon-more"></text>
      </view>
    </view>

    <!-- 任务统计卡片 -->
    <view class="stats-card">
      <view class="stat-item" @click="filterByStatus('active')">
        <text class="stat-number">{{ todayStats.active || 0 }}</text>
        <text class="stat-label">进行中</text>
      </view>
      <view class="stat-divider"></view>
      <view class="stat-item" @click="filterByStatus('completed')">
        <text class="stat-number">{{ todayStats.completed || 0 }}</text>
        <text class="stat-label">已完成</text>
      </view>
      <view class="stat-divider"></view>
      <view class="stat-item" @click="filterByStatus('expired')">
        <text class="stat-number">{{ todayStats.expired || 0 }}</text>
        <text class="stat-label">已过期</text>
      </view>
    </view>

    <!-- 搜索和筛选栏 -->
    <view class="search-filter-bar">
      <view class="search-input-wrapper">
        <text class="iconfont icon-search"></text>
        <input type="text" v-model="searchText" placeholder="搜索任务" @input="onSearch" />
        <text v-if="searchText" class="iconfont icon-clear" @click="clearSearch"></text>
      </view>
      <view class="filter-btn" @click="showFilterModal">
        <text class="iconfont icon-filter"></text>
        <text>{{ getFilterLabel() }}</text>
      </view>
    </view>

    <!-- 分类功能已移除，后端不支持 -->

    <!-- 任务列表 -->
    <scroll-view 
      v-if="tasks.length > 0" 
      class="task-list"
      @scrolltolower="loadMore"
      lower-threshold="100"
    >
      <view 
        v-for="task in tasks" 
        :key="task.id"
        class="task-item"
        :class="{ 
          'expired': task.status === 'expired',
          'completed': task.status === 'completed',
          'urgent': task.priority === 'high' && task.status === 'active'
        }"
        @click="onTaskClick(task)"
        @longpress="onLongPress(task, $event)"
      >
        <!-- 任务完成复选框 -->
        <view class="checkbox-wrapper" @click.stop="toggleTaskStatus(task)">
          <view class="checkbox" :class="{ checked: task.status === 'completed' }">
            <text v-if="task.status === 'completed'" class="iconfont icon-check"></text>
          </view>
        </view>

        <!-- 任务内容 -->
        <view class="task-content">
          <text class="task-title" :class="{ 'line-through': task.status === 'completed' }">{{ task.title }}</text>
          
          <view class="task-meta">
            <view v-if="task.dueTime" class="meta-item">
              <text class="iconfont icon-clock"></text>
              <text>{{ formatDueTime(task.dueTime) }}</text>
            </view>
            
            <!-- 分类和标签功能已移除，后端不支持 -->
          </view>

          <view v-if="task.description" class="task-description">
            {{ task.description }}
          </view>
        </view>

        <!-- 任务优先级和操作 -->
        <view class="task-actions">
          <view 
            class="priority-indicator" 
            :class="`priority-${task.priority}`"
            v-if="task.status !== 'completed'"
          ></view>
          <text v-if="isEditMode" class="iconfont icon-delete" @click.stop="onDeleteTask(task.id)"></text>
        </view>
      </view>

      <view v-if="loading" class="loading-more">加载中...</view>
      <view v-if="!loading && !hasMore" class="no-more">没有更多了</view>
    </scroll-view>

    <!-- 空状态 -->
    <view v-else-if="!loading" class="empty-state">
      <text class="iconfont icon-empty"></text>
      <text class="empty-text">暂无任务</text>
      <text class="empty-subtitle">点击下方按钮创建第一个任务</text>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading && tasks.length === 0" class="loading">
      <view class="loading-spinner"></view>
      <text>加载中...</text>
    </view>

    <!-- 创建任务按钮 -->
    <view class="create-task-btn" @click="createTask">
      <text class="iconfont icon-plus"></text>
    </view>

    <!-- 编辑模式操作栏 -->
    <view v-if="isEditMode" class="edit-bar">
      <view class="select-all">
        <checkbox :checked="isAllSelected" @tap="toggleSelectAll" />
        <text>全选</text>
      </view>
      <view class="edit-actions">
        <button class="action-btn complete-btn" @click="batchComplete" :disabled="selectedTasks.length === 0">
          完成
        </button>
        <button class="action-btn delete-btn" @click="batchDelete" :disabled="selectedTasks.length === 0">
          删除({{ selectedTasks.length }})
        </button>
      </view>
    </view>

    <!-- 操作菜单 -->
    <view class="action-menu" v-if="showActionMenu">
      <view class="menu-content">
        <view class="menu-item" @click="showSortModal">
          <text class="iconfont icon-sort"></text>
          <text>排序方式</text>
        </view>
        <view class="menu-item" @click="showCategoryModal">
          <text class="iconfont icon-category"></text>
          <text>任务分类</text>
        </view>
        <view class="menu-item" @click="refreshTasks">
          <text class="iconfont icon-refresh"></text>
          <text>刷新列表</text>
        </view>
        <view class="menu-item" @click="exportTasks">
          <text class="iconfont icon-export"></text>
          <text>导出任务</text>
        </view>
        <view class="menu-item cancel" @click="hideActions">
          <text>取消</text>
        </view>
      </view>
    </view>

    <!-- 筛选弹窗 -->
    <uni-popup ref="filterPopup" type="bottom" :maskClick="false">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">筛选任务</text>
          <text class="popup-close" @click="closeFilterModal">✕</text>
        </view>
        
        <!-- 状态筛选 -->
        <view class="filter-section">
          <text class="filter-title">任务状态</text>
          <view class="filter-options">
            <view 
              v-for="status in statusOptions" 
              :key="status.value"
              class="filter-option"
              :class="{ active: filters.status === status.value }"
              @click="selectFilter('status', status.value)"
            >
              {{ status.label }}
            </view>
          </view>
        </view>

        <!-- 优先级筛选 -->
        <view class="filter-section">
          <text class="filter-title">优先级</text>
          <view class="filter-options">
            <view 
              v-for="priority in priorityOptions" 
              :key="priority.value"
              class="filter-option"
              :class="{ active: filters.priority === priority.value }"
              @click="selectFilter('priority', priority.value)"
            >
              {{ priority.label }}
            </view>
          </view>
        </view>

        <!-- 日期筛选 -->
        <view class="filter-section">
          <text class="filter-title">日期范围</text>
          <view class="date-filters">
            <view 
              v-for="date in dateOptions" 
              :key="date.value"
              class="date-filter"
              :class="{ active: filters.dateRange === date.value }"
              @click="selectFilter('dateRange', date.value)"
            >
              {{ date.label }}
            </view>
          </view>
        </view>

        <!-- 确认按钮 -->
        <view class="popup-actions">
          <button class="reset-btn" @click="resetFilters">重置</button>
          <button class="confirm-btn" @click="applyFilters">确认筛选</button>
        </view>
      </view>
    </uni-popup>

    <!-- 排序弹窗 -->
    <uni-popup ref="sortPopup" type="bottom" :maskClick="false">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">任务排序</text>
          <text class="popup-close" @click="closeSortModal">✕</text>
        </view>
        
        <view class="sort-options">
          <view 
            v-for="sort in sortOptions" 
            :key="sort.value"
            class="sort-option"
            :class="{ active: currentSort === sort.value }"
            @click="selectSort(sort.value)"
          >
            <text>{{ sort.label }}</text>
            <text v-if="currentSort === sort.value" class="iconfont icon-check"></text>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onShow } from 'vue';
import { useRouter } from 'vue-router';
import taskApi from '../../api/task';
import { showToast, confirm, showLoading, hideLoading } from '../../utils/uni';
// 导入uni-popup组件
import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';

const router = useRouter();

// 响应式数据
const tasks = ref([]);
const loading = ref(false);
const hasMore = ref(true);
const currentPage = ref(1);
const searchText = ref('');
const selectedCategory = ref('');
const isEditMode = ref(false);
const selectedTasks = ref([]);
const showActionMenu = ref(false);
const filterPopup = ref(null);
const sortPopup = ref(null);
const todayStats = ref({ active: 0, completed: 0, expired: 0 });
const currentSort = ref('dueTime');

// 筛选条件
const filters = ref({
  status: 'all',
  priority: 'all',
  dateRange: 'all'
});

// 选项数据
const statusOptions = [
  { label: '全部', value: 'all' },
  { label: '进行中', value: 'active' },
  { label: '已完成', value: 'completed' },
  { label: '已过期', value: 'expired' }
];

const priorityOptions = [
  { label: '全部', value: 'all' },
  { label: '高', value: 'high' },
  { label: '中', value: 'medium' },
  { label: '低', value: 'low' }
];

const dateOptions = [
  { label: '全部', value: 'all' },
  { label: '今天', value: 'today' },
  { label: '明天', value: 'tomorrow' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' },
  { label: '过期', value: 'expired' }
];

const sortOptions = [
  { label: '按截止时间', value: 'dueTime' },
  { label: '按创建时间', value: 'createTime' },
  { label: '按优先级', value: 'priority' }
];

// 计算属性
const isAllSelected = computed(() => {
  return tasks.value.length > 0 && tasks.value.every(task => selectedTasks.value.includes(task.id));
});

// 方法
const loadTasks = async (reset = false) => {
  if (loading.value) return;
  
  loading.value = true;
  
  try {
    if (reset) {
      currentPage.value = 1;
      hasMore.value = true;
    }
    
    // 获取当前用户ID，这里假设从本地存储获取
    const userId = uni.getStorageSync('userId') || '1'; // 默认用户ID
    
    // 根据筛选条件调用不同的API
    let res;
    if (filters.value.dateRange && filters.value.dateRange !== 'all') {
      // 日期范围查询
      const dateRange = getDateRange(filters.value.dateRange);
      res = await taskApi.getUserTasksByRange(userId, dateRange.startDate, dateRange.endDate);
    } else if (filters.value.status === 'pending') {
      // 待完成任务
      res = await taskApi.getUserPendingTasks(userId);
    } else {
      // 普通任务列表
      res = await taskApi.getUserTasks(userId);
    }
    
    // 处理优先级筛选
    let filteredTasks = res.data || [];
    if (filters.value.priority && filters.value.priority !== 'all') {
      filteredTasks = filteredTasks.filter(task => task.priority === filters.value.priority);
    }
    
    // 处理状态筛选
    if (filters.value.status && filters.value.status !== 'all' && filters.value.status !== 'pending') {
      const statusMap = {
        'active': 0,  // 未开始
        'completed': 1,  // 已完成
        'expired': 0  // 后端没有过期状态，前端处理
      };
      filteredTasks = filteredTasks.filter(task => task.status === statusMap[filters.value.status]);
      
      // 额外处理过期任务
      if (filters.value.status === 'expired') {
        const now = new Date();
        filteredTasks = filteredTasks.filter(task => {
          const endTime = task.endTime ? new Date(task.endTime) : null;
          return endTime && endTime < now;
        });
      }
    }
    
    // 处理搜索
    if (searchText.value) {
      const searchLower = searchText.value.toLowerCase();
      filteredTasks = filteredTasks.filter(task => 
        task.title.toLowerCase().includes(searchLower) ||
        (task.description && task.description.toLowerCase().includes(searchLower))
      );
    }
    
    // 处理排序
    if (currentSort.value) {
      filteredTasks.sort((a, b) => {
        switch (currentSort.value) {
          case 'dueTime':
            return new Date(a.endTime || 0) - new Date(b.endTime || 0);
          case 'createTime':
            return new Date(b.createTime) - new Date(a.createTime); // 最新的在前
          case 'priority':
            const priorityMap = { high: 3, medium: 2, low: 1 };
            return (priorityMap[b.priority] || 0) - (priorityMap[a.priority] || 0);
          default:
            return 0;
        }
      });
    }
    
    // 简单的分页处理（由于后端可能不支持分页，前端模拟）
    const pageSize = 20;
    const start = (currentPage.value - 1) * pageSize;
    const end = start + pageSize;
    const paginatedTasks = filteredTasks.slice(start, end);
    
    if (reset) {
      tasks.value = paginatedTasks;
    } else {
      tasks.value = [...tasks.value, ...paginatedTasks];
    }
    
    hasMore.value = end < filteredTasks.length;
    
    if (hasMore.value) {
      currentPage.value++;
    }
  } catch (error) {
    showToast('加载任务列表失败', 'error');
    console.error('Failed to load tasks:', error);
  } finally {
    loading.value = false;
  }
};

// 获取日期范围
const getDateRange = (dateRange) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);
  
  const weekStart = new Date(today);
  weekStart.setDate(today.getDate() - today.getDay());
  
  const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
  const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0);
  monthEnd.setHours(23, 59, 59, 999);
  
  switch (dateRange) {
    case 'today':
      return {
        startDate: today.toISOString(),
        endDate: new Date(today.setHours(23, 59, 59, 999)).toISOString()
      };
    case 'tomorrow':
      return {
        startDate: tomorrow.toISOString(),
        endDate: new Date(tomorrow.setHours(23, 59, 59, 999)).toISOString()
      };
    case 'week':
      return {
        startDate: weekStart.toISOString(),
        endDate: new Date(today.setHours(23, 59, 59, 999)).toISOString()
      };
    case 'month':
      return {
        startDate: monthStart.toISOString(),
        endDate: monthEnd.toISOString()
      };
    default:
      return {
        startDate: null,
        endDate: null
      };
  }
};

const loadTodayStats = async () => {
  try {
    // 获取当前用户ID
    const userId = uni.getStorageSync('userId') || '1';
    
    const res = await taskApi.getUserTasks(userId);
    const allTasks = res.data || [];
    
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    // 计算今日任务统计
    todayStats.value = {
      active: allTasks.filter(task => {
        const taskEndTime = task.endTime ? new Date(task.endTime) : null;
        return task.status === 0 && taskEndTime && taskEndTime >= today && taskEndTime < tomorrow;
      }).length,
      completed: allTasks.filter(task => {
        const taskEndTime = task.endTime ? new Date(task.endTime) : null;
        return task.status === 1 && taskEndTime && taskEndTime >= today && taskEndTime < tomorrow;
      }).length,
      expired: allTasks.filter(task => {
        const taskEndTime = task.endTime ? new Date(task.endTime) : null;
        return task.status === 0 && taskEndTime && taskEndTime < today;
      }).length
    };
  } catch (error) {
    console.error('Failed to load today stats:', error);
  }
};

const onSearch = () => {
  clearTimeout(onSearch.timer);
  onSearch.timer = setTimeout(() => {
    loadTasks(true);
  }, 500);
};

const clearSearch = () => {
  searchText.value = '';
  loadTasks(true);
};

const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId;
  loadTasks(true);
};

const filterByStatus = (status) => {
  filters.value.status = status === 'all' ? 'all' : status;
  loadTasks(true);
};

const showFilterModal = () => {
  filterPopup.value?.open();
};

const closeFilterModal = () => {
  filterPopup.value?.close();
};

const selectFilter = (key, value) => {
  filters.value[key] = value;
};

const resetFilters = () => {
  filters.value = {
    status: 'all',
    priority: 'all',
    dateRange: 'all'
  };
};

const applyFilters = () => {
  closeFilterModal();
  loadTasks(true);
};

const showSortModal = () => {
  hideActions();
  sortPopup.value?.open();
};

const closeSortModal = () => {
  sortPopup.value?.close();
};

const selectSort = (sortBy) => {
  currentSort.value = sortBy;
  closeSortModal();
  loadTasks(true);
};

const showCategoryModal = () => {
  hideActions();
  router.push('/pages/task/categoryManage');
};

const loadMore = () => {
  if (hasMore.value && !loading.value) {
    loadTasks(false);
  }
};

const refreshTasks = () => {
  hideActions();
  loadTasks(true);
  loadTodayStats();
};

const exportTasks = () => {
  hideActions();
  showToast('导出功能暂未实现', 'info');
};

const onTaskClick = (task) => {
  if (isEditMode.value) {
    toggleSelectTask(task.id);
  } else {
    goToTaskDetail(task.id);
  }
};

const onLongPress = (task, event) => {
  event.stopPropagation();
  
  if (!isEditMode.value) {
    enterEditMode();
    selectedTasks.value = [task.id];
  }
};

const toggleTaskStatus = async (task) => {
  try {
    const newStatus = task.status === 'completed' ? 'active' : 'completed';
    await taskApi.updateTaskStatus(task.id, newStatus);
    
    // 更新本地任务状态
    task.status = newStatus;
    
    // 更新统计数据
    loadTodayStats();
    
    showToast(newStatus === 'completed' ? '任务已完成' : '任务已重新激活');
  } catch (error) {
    showToast('更新任务状态失败', 'error');
    console.error('Failed to toggle task status:', error);
  }
};

const createTask = () => {
  router.push('/pages/task/taskEdit');
};

const goToTaskDetail = (taskId) => {
  router.push(`/pages/task/taskDetail?id=${taskId}`);
};

const goBack = () => {
  if (isEditMode.value) {
    exitEditMode();
  } else {
    router.back();
  }
};

const enterEditMode = () => {
  isEditMode.value = true;
  selectedTasks.value = [];
};

const exitEditMode = () => {
  isEditMode.value = false;
  selectedTasks.value = [];
};

const toggleSelectTask = (taskId) => {
  const index = selectedTasks.value.indexOf(taskId);
  if (index > -1) {
    selectedTasks.value.splice(index, 1);
  } else {
    selectedTasks.value.push(taskId);
  }
};

const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedTasks.value = [];
  } else {
    selectedTasks.value = tasks.value.map(task => task.id);
  }
};

const batchComplete = async () => {
  if (selectedTasks.value.length === 0) return;
  
  try {
    await taskApi.batchUpdateTaskStatus(selectedTasks.value, 'completed');
    
    // 更新本地任务状态
    tasks.value.forEach(task => {
      if (selectedTasks.value.includes(task.id)) {
        task.status = 'completed';
      }
    });
    
    selectedTasks.value = [];
    loadTodayStats();
    showToast('任务已批量标记为完成');
  } catch (error) {
    showToast('批量更新失败', 'error');
    console.error('Failed to batch complete tasks:', error);
  }
};

const batchDelete = async () => {
  if (selectedTasks.value.length === 0) return;
  
  const confirmed = await confirm(`确定要删除选中的 ${selectedTasks.value.length} 个任务吗？`);
  if (!confirmed) return;
  
  try {
    await taskApi.batchDeleteTasks(selectedTasks.value);
    
    // 从列表中移除删除的任务
    tasks.value = tasks.value.filter(task => !selectedTasks.value.includes(task.id));
    
    selectedTasks.value = [];
    loadTodayStats();
    showToast('任务已批量删除');
    
    // 如果列表为空，退出编辑模式
    if (tasks.value.length === 0) {
      exitEditMode();
    }
  } catch (error) {
    showToast('批量删除失败', 'error');
    console.error('Failed to batch delete tasks:', error);
  }
};

const onDeleteTask = async (taskId) => {
  const confirmed = await confirm('确定要删除这个任务吗？');
  if (!confirmed) return;
  
  try {
    await taskApi.deleteTask(taskId);
    
    // 从列表中移除删除的任务
    tasks.value = tasks.value.filter(task => task.id !== taskId);
    
    // 从选中列表中移除
    selectedTasks.value = selectedTasks.value.filter(id => id !== taskId);
    
    loadTodayStats();
    showToast('任务已删除');
    
    // 如果列表为空，退出编辑模式
    if (tasks.value.length === 0) {
      exitEditMode();
    }
  } catch (error) {
    showToast('删除任务失败', 'error');
    console.error('Failed to delete task:', error);
  }
};

const showActions = () => {
  showActionMenu.value = true;
};

const hideActions = () => {
  showActionMenu.value = false;
};

const getFilterLabel = () => {
  let label = '筛选';
  const activeFilters = [];
  
  if (filters.value.status !== 'all') {
    const status = statusOptions.find(s => s.value === filters.value.status);
    if (status) activeFilters.push(status.label);
  }
  
  if (filters.value.priority !== 'all') {
    const priority = priorityOptions.find(p => p.value === filters.value.priority);
    if (priority) activeFilters.push(priority.label);
  }
  
  if (filters.value.dateRange !== 'all') {
    const date = dateOptions.find(d => d.value === filters.value.dateRange);
    if (date) activeFilters.push(date.label);
  }
  
  if (activeFilters.length > 0) {
    label = activeFilters.join(',');
  }
  
  return label;
};

const formatDueTime = (time) => {
  if (!time) return '';
  
  const now = new Date();
  const due = new Date(time);
  const diffDays = Math.floor((due - now) / (1000 * 60 * 60 * 24));
  
  // 今天
  if (diffDays === 0) {
    return `今天 ${due.getHours().toString().padStart(2, '0')}:${due.getMinutes().toString().padStart(2, '0')}`;
  }
  // 明天
  else if (diffDays === 1) {
    return `明天 ${due.getHours().toString().padStart(2, '0')}:${due.getMinutes().toString().padStart(2, '0')}`;
  }
  // 本周内
  else if (diffDays > 1 && diffDays < 7) {
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    return `周${weekdays[due.getDay()]}`;
  }
  // 本月内
  else if (due.getMonth() === now.getMonth() && due.getFullYear() === now.getFullYear()) {
    return `${due.getDate()}日`;
  }
  // 今年内
  else if (due.getFullYear() === now.getFullYear()) {
    return `${due.getMonth() + 1}月${due.getDate()}日`;
  }
  // 其他
  else {
    return `${due.getFullYear()}/${due.getMonth() + 1}/${due.getDate()}`;
  }
};

// 生命周期
onMounted(() => {
  loadCategories();
  loadTodayStats();
});

onShow(() => {
  loadTasks(true);
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.back-btn,
.action-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-btn .iconfont,
.action-btn .iconfont {
  font-size: 36rpx;
  color: #333;
}

.navbar .title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.stats-card {
  display: flex;
  background-color: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #4a90e2;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 28rpx;
  color: #666;
}

.stat-divider {
  width: 2rpx;
  background-color: #f0f0f0;
  margin: 0 20rpx;
}

.search-filter-bar {
  display: flex;
  padding: 0 20rpx 20rpx;
  align-items: center;
}

.search-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 80rpx;
  padding: 16rpx 24rpx;
  margin-right: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.search-input-wrapper .iconfont {
  font-size: 32rpx;
  color: #999;
  margin-right: 16rpx;
}

.search-input-wrapper input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.filter-btn {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background-color: #fff;
  border-radius: 80rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  font-size: 28rpx;
  color: #666;
}

.filter-btn .iconfont {
  font-size: 32rpx;
  margin-right: 8rpx;
}

.category-tabs {
  padding: 0 20rpx 20rpx;
  white-space: nowrap;
}

.tab-item {
  display: inline-flex;
  align-items: center;
  padding: 12rpx 32rpx;
  margin-right: 16rpx;
  background-color: #fff;
  border-radius: 60rpx;
  font-size: 28rpx;
  color: #666;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.tab-item.active {
  background-color: #4a90e2;
  color: #fff;
}

.tab-badge {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  min-width: 32rpx;
  height: 32rpx;
  padding: 0 10rpx;
  background-color: #ff6b6b;
  color: #fff;
  font-size: 20rpx;
  border-radius: 16rpx;
  line-height: 32rpx;
}

.task-list {
  padding: 0 20rpx;
}

.task-item {
  display: flex;
  padding: 24rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: background-color 0.2s;
  position: relative;
}

.task-item.expired {
  background-color: #fff5f5;
}

.task-item.completed {
  background-color: #f5fff5;
}

.task-item.urgent {
  border-left: 8rpx solid #ff6b6b;
}

.checkbox-wrapper {
  margin-right: 20rpx;
  padding-top: 4rpx;
}

.checkbox {
  width: 44rpx;
  height: 44rpx;
  border: 4rpx solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox.checked {
  background-color: #4a90e2;
  border-color: #4a90e2;
}

.checkbox.checked .iconfont {
  color: #fff;
  font-size: 24rpx;
}

.task-content {
  flex: 1;
}

.task-title {
  display: block;
  font-size: 32rpx;
  color: #333;
  margin-bottom: 12rpx;
  font-weight: 500;
}

.task-title.line-through {
  text-decoration: line-through;
  color: #999;
}

.task-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 12rpx;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-right: 20rpx;
  margin-bottom: 8rpx;
}

.meta-item .iconfont {
  font-size: 24rpx;
  color: #999;
  margin-right: 8rpx;
}

.meta-item text {
  font-size: 24rpx;
  color: #666;
}

.category-tag {
  padding: 4rpx 16rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
  color: #fff;
}

.tag {
  padding: 4rpx 16rpx;
  background-color: #f0f0f0;
  border-radius: 12rpx;
  font-size: 24rpx;
  color: #666;
  margin-right: 8rpx;
}

.tag-more {
  font-size: 24rpx;
  color: #999;
}

.task-description {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.task-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-left: 20rpx;
  justify-content: space-between;
  min-width: 40rpx;
}

.priority-indicator {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
}

.priority-high {
  background-color: #ff6b6b;
}

.priority-medium {
  background-color: #fbc02d;
}

.priority-low {
  background-color: #4caf50;
}

.task-actions .icon-delete {
  font-size: 36rpx;
  color: #ff6b6b;
  margin-top: 20rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-state .iconfont {
  font-size: 120rpx;
  color: #ccc;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.empty-subtitle {
  font-size: 28rpx;
  color: #999;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #4a90e2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-more,
.no-more {
  text-align: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #999;
}

.create-task-btn {
  position: fixed;
  bottom: 40rpx;
  right: 40rpx;
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #4a90e2;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 20rpx rgba(74, 144, 226, 0.4);
  z-index: 100;
}

.create-task-btn .iconfont {
  font-size: 60rpx;
  color: #fff;
}

.edit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.select-all {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #666;
}

.select-all checkbox {
  margin-right: 10rpx;
}

.edit-actions {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  font-size: 28rpx;
  padding: 0 30rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
}

.complete-btn {
  background-color: #4caf50;
  color: #fff;
}

.delete-btn {
  background-color: #ff6b6b;
  color: #fff;
}

.action-btn:disabled {
  background-color: #ccc;
}

.action-menu,
.popup-content {
  background-color: #fff;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;
}

.menu-content {
  padding: 30rpx;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 2rpx solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
  margin-top: 20rpx;
}

.menu-item .iconfont {
  font-size: 36rpx;
  color: #4a90e2;
  margin-right: 20rpx;
  width: 40rpx;
  text-align: center;
}

.menu-item .icon-check {
  color: #4a90e2;
  margin-right: 0;
  width: auto;
}

.menu-item text {
  font-size: 32rpx;
  color: #333;
}

.menu-item.cancel text {
  color: #999;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 40rpx;
  color: #999;
}

.filter-section {
  padding: 30rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.filter-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.filter-option {
  padding: 12rpx 32rpx;
  background-color: #f5f5f5;
  border-radius: 60rpx;
  font-size: 28rpx;
  color: #666;
}

.filter-option.active {
  background-color: #4a90e2;
  color: #fff;
}

.date-filters {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
}

.date-filter {
  padding: 16rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #666;
  text-align: center;
}

.date-filter.active {
  background-color: #4a90e2;
  color: #fff;
}

.popup-actions {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
}

.popup-actions button {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
}

.reset-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #4a90e2;
  color: #fff;
}

.sort-options {
  padding: 30rpx;
}

.sort-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 0;
  border-bottom: 2rpx solid #f0f0f0;
}

.sort-option:last-child {
  border-bottom: none;
}

.sort-option text {
  font-size: 32rpx;
  color: #333;
}

.sort-option .icon-check {
  color: #4a90e2;
}
</style>